﻿using System.Web.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Marbles.Core.Web.Resources;

namespace Marbles.Core.Web.MVC.Views
{
    public abstract class View : ViewBase, IView
    {

        public Models.Model Model
        {
            get { return this._model; }
        }

        private Models.Model _model = null;

        internal void InitialiseModel(Models.Model Model)
        {
            this._model = Model;
            Model.Load(this, EventArgs.Empty);
        }

        public abstract void InitialiseView(object sender, ViewInitialiseEventArgs e);

        protected override void OnLoad(EventArgs e)
        {            
            if (this.Model == null)
            {
                throw new InvalidOperationException("Unable to invoke View without Model.");
            }

            bool isAsyncRequest = false;

            if (!this.IsHeaderScriptIncludeRegistered("jQuery"))
            {
                jQueryLibraryResource jQueryLibrary = new jQueryLibraryResource();
                this.RegisterHeaderScriptInclude("jQuery", jQueryLibrary.jQueryResourceUrl);
                this.RegisterHeaderCSSInclude("jQueryCSS", jQueryLibrary.jQueryCSSResourceUrl);
            }

            if (this.Request["X-MicrosoftAjax"] != null)
            {
                if (this.Request["X-MicrosoftAjax"] == "delta-true") { isAsyncRequest = true; }
            }

            InitialiseView(this, new ViewInitialiseEventArgs(Page.IsPostBack, isAsyncRequest, Page.IsCallback));

            base.OnLoad(e);
        }

        protected override void OnUnload(EventArgs e)
        {
            if (Model != null) { Model.UnLoad(this, e); }
        }

        protected override bool OnBubbleEvent(object source, EventArgs args)
        {
            return base.OnBubbleEvent(source, args);
        }
    }
}
